<template>
  <div>
    <uni-section title="基本信息" type="line">
      <form>
        <!-- 服务类型 -->
        <view class="formItem">
          <view class="label required">服务类型</view>
          <ld-select class="content" :multiple="false" :list="serviceType" label-key="dictLabel" value-key="dictValue"
            placeholder="请选择服务类型" v-model="valiFormData.serviceType" @change="serviceTypeChange"></ld-select>
        </view>

        <!-- 项目名称-->
        <view class="formItem">
          <view class="label required">项目名称</view>
          <input class="content" v-model="valiFormData.name" placeholder="请输入项目名称"
            @blur="labelLength('项目名称', valiFormData.name, true, 64)" />
        </view>

        <!-- 项目类型-->
        <view class="formItem">
          <view class="label required">项目类型</view>
          <ld-select class="content" :multiple="false" :list="projectList" label-key="dictLabel" value-key="dictValue"
            placeholder="请选择项目类型" v-model="valiFormData.type" @change="projectTypeChange"></ld-select>
        </view>

        <!-- 项目负责人 -->
        <view class="formItem">
          <view class="label required">项目负责人</view>
          <picker mode="selector" class="content" :range="leaderList" range-key="name" @change="leaderChange($event)">
            <view :style="{ 'color': valiFormData.showLeader ? '#333' : '#999' }">{{ valiFormData.showLeader ||
              '请选择项目负责人' }}</view>
          </picker>
        </view>

        <!-- 项目所在地区 -->
        <view class="formItem" v-if="show">
          <view class="label required">项目所在地区</view>
          <view :style="{ color: valiFormData.areas ? '#333' : '#999' }" style="text-align: right; width: 57%"
            @click="openLevel">
            {{ valiFormData.areas ||
              '请选择所在区域' }}</view>
          <level-linkage ref="levelLinkage" :pickerValueDefault="pickerValueDefault" :allData="treeData"
            @onConfirm="onConfirm" themeColor='#007AFF'></level-linkage>
        </view>

        <!-- 项目详细地址 -->
        <view class="formItem" @click="chooseMap('1')">
          <view class="label required">项目详细地址</view>
          <input class="content" v-model="valiFormData.address" placeholder="项目详细地址"
            @blur="labelLength('项目详细地址', valiFormData.address, true, 64)" />
        </view>

        <!-- 执业场所 -->
        <view class="formItem" @click="chooseMap('2')">
          <view class="label ">执业场所</view>
          <input class="content" v-model="valiFormData.placeLonLat" disabled placeholder="执业场所" />
          <!-- @blur="labelLength('项目详细地址', valiFormData.address, true, 64)" -->
        </view>

        <!-- 执业场所详细地址 -->
        <view class="formItem">
          <view class="label ">执业场所详细地址</view>
          <input class="content" v-model="valiFormData.placeName" placeholder="执业场所详细地址"
            @blur="labelLength('执业场所详细地址', valiFormData.placeName, true, 64)" />
        </view>

        <!-- 技术负责人 -->
        <view class="formItem">
          <view class="label required">技术负责人</view>
          <picker mode="selector" class="content" :range="directorList" range-key="name"
            @change="directorChange($event)">
            <view :style="{ color: valiFormData.showDirector ? '#333' : '#999' }">{{ valiFormData.showDirector ?
              valiFormData.showDirector : '请选择技术负责人' }}</view>
          </picker>
        </view>

        <!-- 执业人员 -->
        <view class="formItem">
          <view class="label required">执业人员</view>
          <ld-select class="content" :multiple="true" :list="practList" label-key="name" value-key="staffId"
            placeholder="请选择执业人员" v-model="valiFormData.staffIdList" @change="practChange"></ld-select>
        </view>

        <!-- 建筑使用用途
        <view class="formItem">
          <view class="label required">建筑使用用途</view>
          <input class="content"
                 v-model="valiFormData.buildName"
                 placeholder="请输入建筑使用用途"
                 @blur="labelLength('建筑使用用途', valiFormData.buildName, true, 64)" />
        </view> -->

        <!-- 委托单位 -->
        <view class="formItem">
          <view class="label required">委托单位</view>
          <input class="content" v-model="valiFormData.entrustUnit" placeholder="请输入委托单位"
            @blur="labelLength('委托单位', valiFormData.entrustUnit, true, 64)" />
        </view>

        <!-- 委托单位联系电话 -->
        <view class="formItem">
          <view class="label">委托单位联系电话</view>
          <input class="content" v-model="valiFormData.entrustUnitPhone" placeholder="请输入委托单位联系电话" @blur="
            labelLength(
              '委托单位联系电话',
              valiFormData.entrustUnitPhone,
              true,
              64
            )
            " />
        </view>

        <!-- 委托单位联系人 -->
        <view class="formItem">
          <view class="label required">委托单位联系人</view>
          <input class="content" v-model="valiFormData.entrustContact" placeholder="请输入委托单位联系人" @blur="
            labelLength(
              '委托单位联系人',
              valiFormData.entrustContact,
              true,
              64
            )
            " />
        </view>

        <!-- 委托单位联系人电话 -->
        <view class="formItem">
          <view class="label required">委托单位联系人电话</view>
          <input class="content" v-model="valiFormData.entrustContactPhone" placeholder="请输入委托单位联系人电话" @blur="
            labelLength(
              '委托单位联系人电话',
              valiFormData.entrustContactPhone,
              true,
              64
            )
            " />
        </view>

        <!-- 占地面积(㎡) -->
        <view class="formItem">
          <view class="label">占地面积(㎡)</view>
          <input class="content" v-model="valiFormData.areaCovered" placeholder="请输入占地面积(㎡)" @blur="
            labelLength('占地面积(㎡)', valiFormData.areaCovered, true, 64)
            " />
        </view>

        <!-- 合同编号 -->
        <view class="formItem">
          <view class="label required">合同编号</view>
          <input class="content" v-model="valiFormData.no" placeholder="请输入合同编号"
            @blur="labelLength('合同编号', valiFormData.no, true, 64)" />
        </view>

        <!-- 合同签订日期 -->
        <view class="formItem">
          <view class="label required">合同签订日期</view>
          <picker mode="date" class="content" :value="date" :start="startDate" :end="endDate" @change="signChange">
            <view :style="{ color: valiFormData.showSign ? '#333' : '#999' }">{{ valiFormData.showSign || '请选择合同签订日期' }}
            </view>
          </picker>
        </view>

        <!-- 合同开始时间 -->
        <view class="formItem">
          <view class="label required">合同开始时间</view>
          <picker mode="date" class="content" :value="date" :start="startDate" :end="endDate" @change="startChange">
            <view :style="{ color: valiFormData.showStart ? '#333' : '#999' }">{{ valiFormData.showStart || '请选择合同开始时间'
            }}
            </view>

          </picker>
        </view>

        <!-- 合同结束时间 -->
        <view class="formItem">
          <view class="label required">合同结束时间</view>
          <picker mode="date" class="content" :value="date" :start="startDate" :end="endDate" @change="endChange">
            <view :style="{ color: valiFormData.showEnd ? '#333' : '#999' }">{{ valiFormData.showEnd || '请选择合同结束时间' }}
            </view>
          </picker>
        </view>

        <view style="height: 80rpx"></view>
      </form>
    </uni-section>
    <toast></toast>
    <view class="btn" @click="next">下一步</view>
  </div>
</template>

<script>
import ldSelect from "@/components/ld-select/ld-select";
import levelLinkage from "@/components/three-level-linkage/linkage.nvue"
import { mapState } from "vuex";
export default {
  components: {
    ldSelect,
    levelLinkage
  },
  data() {
    const currentDate = this.getDate({
      format: true,
    });
    return {
      projectList: [], // 项目类型





      date: currentDate,
      // 服务类型列表
      serviceType: [
        {
          text: "维护保养检测",
          value: "1",
        },
        {
          text: "消防安全评估",
          value: "2",
        },
      ],
      // 项目负责人列表
      leaderList: [],
      // 技术负责人列表
      directorList: [],
      // 执业人员列表
      practList: [],

      // 表单数据
      valiFormData: {
        name: "", // 项目名称
        serviceType: null, // 服务类型
        type: null, // 项目类型
        projectHead: null, // 项目负责人
        area: "", // 项目所在地区
        areas: "", // 项目所在地区回显
        address: "", // 项目详细地址
        placeLonLat: null, // 执业场所
        placeName: null, // 执业场所详细地址
        technologyHead: "", // 技术负责人
        staffIdList: [], // 执业人员
        // buildName: null, // 建筑使用用途
        entrustUnit: "", // 委托单位
        entrustUnitPhone: "", // 委托单位联系电话
        entrustContact: "", // 委托单位联系人
        entrustContactPhone: "", // 委托单位联系人电话
        areaCovered: "", // 占地面积(㎡)
        no: "", // 合同编号
        signDate: "", // 合同签订日期
        startDate: "", // 合同开始时间
        endDate: "", // 合同结束时间
        showLeader: "", // 项目负责人回显
        showDirector: "", // 技术负责人回显
        showSign: "", // 合同签订日期回显
        showStart: "", // 合同开始时间回显
        showEnd: "", // 合同结束时间回显
      },

      pickerValueDefault: [0, 0, 0],
      treeData: [], // 所属区域
      treeId: [],
      show: false,
    };
  },
  computed: {
    ...mapState(["task"]),
    startDate() {
      return this.getDate("start");
    },
    endDate() {
      return this.getDate("end");
    },
  },

  created() {
    new Promise((resolve, reject) => {
      this.getTreelists()// 获取项目所在区域
      this.getServerType()// 获取服务类型
      this.getProjectType()// 获取项目类型
      setTimeout(() => {
        resolve();
      }, 500);
    }).then((res) => {
      this.treeId = [];
      if (this.task.firstObj != null) {
        this.valiFormData = this.task.firstObj;
        this.formTree(this.treeData, this.task.firstObj.area)
        let dist = [this.task.firstObj.areaName];
        let newDemo = ['无']
        let demo = this.treeId.concat(dist);
        if (demo.length == 2) {
          demo = demo.concat(newDemo)
        }
        this.$set(this.valiFormData, "areas", demo)
      }
    });

    this.getLeaderInfo();
    this.getPractInfo();
    this.getDirectorInfo();
  },
  methods: {
    getTreelists() {
      this.$store.dispatch('getAreaTreeApi').then(res => {
        this.treeData = res.data
        this.show = true
      })
    },
    // 反向递归
    formTree(list, id) {
      list.forEach((item) => {
        if (item.children && item.children.length) {
          if (item.children.some((row) => row.id === id)) {
            this.treeId.unshift(item.name);
            this.formTree(this.treeData, item.id);
          } else {
            this.formTree(item.children, id);
          }
        } else {
          return;
        }
      });
    },
    openLevel() {
      this.$refs.levelLinkage.open();
    },
    onConfirm(e) {
      // e 确认后选中的数据
      this.valiFormData.areas = e.name
      this.valiFormData.area = e.thirdPick.id
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === "start") {
        year = year - 60;
      } else if (type === "end") {
        year = year + 2;
      }
      month = month > 9 ? month : "0" + month;
      day = day > 9 ? day : "0" + day;
      return `${year}-${month}-${day}`;
    },
    // 校验（label:描述，prop:属性值，length:字符长度,isLength:是否进行字符长度判断）
    labelLength(label, prop, isLength, length) {
      return new Promise((resovle, reject) => {
        if (prop.length == 0) {
          reject(label + "不能为空");

          this.$showToast({
            show: true,
            text: label + "不能为空",
          });
        } else {
          resovle(true);
        }
        // 如果为真进行长度判断
        if (isLength) {
          if (prop.length > length) {
            reject(label + "不能长于" + length + "字符");

            this.$showToast({
              show: true,
              text: label + "不能长于" + length + "字符",
            });
          } else {
            resovle(true);
          }
        }
      });
    },
    // 选择项目负责人change
    leaderChange(e) {
      if (
        this.valiFormData.technologyHead ==
        this.leaderList[e.detail.value].staffId
      ) {
        uni.showToast({
          title: `当前负责人已经是技术负责人了`,
          icon: "none",
        });
      } else {
        this.valiFormData.projectHead = this.leaderList[e.detail.value].staffId;
        this.valiFormData.showLeader = this.leaderList[e.detail.value].name;
      }
    },
    // 技术负责人change
    directorChange(e) {
      if (
        this.valiFormData.projectHead ==
        this.directorList[e.detail.value].staffId
      ) {
        uni.showToast({
          title: `当前负责人已经是项目负责人了`,
          icon: "none",
        });
      } else {
        this.valiFormData.technologyHead =
          this.directorList[e.detail.value].staffId;
        this.valiFormData.showDirector = this.directorList[e.detail.value].name;
      }
    },
    // 执业人员change
    practChange(value) {
      this.valiFormData.staffIdList = value;
    },
    // 服务类型change
    serviceTypeChange(value) {
      this.valiFormData.serviceType = value;
    },
    // 合同签订日期change
    signChange(e) {
      this.valiFormData.signDate = e.detail.value;
      this.valiFormData.showSign = e.detail.value;
    },
    // 合同开始时间change
    startChange(e) {
      this.valiFormData.startDate = e.detail.value;
      this.valiFormData.showStart = e.detail.value;
    },
    // 合同结束时间change
    endChange(e) {
      this.valiFormData.endDate = e.detail.value;
      this.valiFormData.showEnd = e.detail.value;
    },

    // 异步获取项目负责人列表信息
    getLeaderInfo() {
      let data = {
        pageNo: 1,
        pageSize: 100000,
        state: "1",
        registeredFireEngineer: "1",
      };
      this.$store.dispatch("getLeaderList", data).then(({ data }) => {
        this.leaderList = data.items;
      });
    },
    // 异步获取技术负责人列表信息
    getDirectorInfo() {
      let data = {
        pageNo: 1,
        pageSize: 100000,
        state: "1",
        isResponsible: "是",
      };
      this.$store.dispatch("getLeaderList", data).then(({ data }) => {
        this.directorList = data.items;
      });
    },
    // 异步获取执业人员列表信息
    getPractInfo() {
      let data = {
        pageNo: 1,
        pageSize: 100000,
        state: "1",
      };
      this.$store.dispatch("getLeaderList", data).then(({ data }) => {
        this.practList = data.items;
      });
    },

    next() {
      // 校验是否通过
      let result = true;
      // 如果表单字段为空时则返回校验失败
      for (const key in this.valiFormData) {
        // 跳过id校验、占地面积(㎡)、委托单位联系电话
        if (this.valiFormData[key] === "" || !this.valiFormData[key]) {
          if (key == "projectId" || key == 'areaCovered' || key == 'entrustUnitPhone' || key == 'placeLonLat' || key == 'placeName') {
            result = true;
          } else {
            result = false;
            break;
          }
        }
        if (result === false) break;
      }
      if (result) {
        // 将服务类型转化成字符串
        if (this.valiFormData.serviceType instanceof Array) {
          this.valiFormData.serviceType =
            this.valiFormData.serviceType.join(",");
        }
        this.$store.commit("storeFirst", this.valiFormData);
        this.$emit("changeNext", 1);
      } else {
        this.$showToast({
          show: true,
          text: "信息未填写完整，请完善后再保存！",
        });
      }
    },


    // 获取服务类型
    getServerType() {
      this.$getDict('service_type').then(res => {
        this.serviceType = res
      })
    },
    // 获取项目类型
    getProjectType() {
      this.$getDict('project_type').then(res => {
        this.projectList = res
      })
    },
    // 项目类型的change
    projectTypeChange(value) {
      this.valiFormData.type = value;
    },
    // 选择企业地理坐标
    chooseMap(key) {
      let that = this
      uni.getLocation({
        type: "gcj02", //返回可以用于uni.openLocation的经纬度
        success: function (res) {
          const latitude = res.latitude;
          const longitude = res.longitude;
          uni.chooseLocation({
            latitude: latitude,
            longitude: longitude,
            success: (res) => {
              if (res) {
                if (key == '1') {
                  that.valiFormData.address = res.address;
                } else if (key == '2') {
                  that.valiFormData.placeLonLat = res.latitude + "," + res.longitude;
                  that.valiFormData.placeName = res.address;
                }
              }
            },
            fail: (e) => {
              console.log(e)
            }
          });
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.formItem {
  display: flex;
  align-items: center;
  min-height: 110rpx;
  width: 710rpx;
  margin: 0 auto 12rpx;
  background-color: #fff;
  padding: 0 22rpx;
  border-radius: 20rpx;

  .label {
    color: #333;
    font-size: 28rpx;
    font-weight: 400;
    line-height: 36rpx;
    width: 43%;
  }

  .content {
    flex: 1;
    text-align: right;
    font-size: 28rpx;
  }
}

.btn {
  position: fixed;
  bottom: 0;
  z-index: 99;
  width: calc(100% - 40rpx);
  margin: 0 20rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  height: 80rpx;
  text-align: center;
  color: #fff;
  font-size: 30rpx;
  font-family: Source Han Sans CN;
  font-weight: 400;
  background: $OVERALL_CONFIRM_BUTTON_COLOR;
}

.required {
  &::after {
    content: "*";
    margin: 0 10rpx;
    color: #ea0707;
  }
}
</style>
